package org.ofbiz.steel.generate;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class FreemarkerTemplateUtils {

	private static String defaultCharacter = "UTF-8";
	private static Configuration cfg;

	public static final String OFBIZ_HOME = System.getProperty("ofbiz.home");

	static String generateCodeTemplatePath = OFBIZ_HOME + "/applications/steel/config/code-template-auto";

//    public static void main(String args[]) throws IOException, TemplateException {
//	FreemarkerUtils obj = new FreemarkerUtils();
//	obj.init();
//	Map<String, Object> map = new HashMap<String, Object>();
//	map.put("entityName", "11111");
//	map.put("tableName", "11111");
//	map.put("entityPackage", "11111");
//
//	Template t = obj.getCfg().getTemplate("default/one/java/TestInclude.ftl");
//	Writer out = new StringWriter();
//	t.process(map, out);
//	System.out.println(out);
//    }

	public static String processTemplate(String myTemplate, Map<String, Object> map) {
		String result = null;
		try {
			if (myTemplate.contains(generateCodeTemplatePath)) {
				myTemplate = myTemplate.replace(generateCodeTemplatePath, "");
			}
			FreemarkerTemplateUtils obj = new FreemarkerTemplateUtils();
			obj.init();
			Template t = obj.getCfg().getTemplate(myTemplate, "UTF-8");
			Writer out = new StringWriter();
			t.process(map, out);
			out.flush();
			result = out.toString();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@SuppressWarnings("deprecation")
	public void init() throws IOException {
		cfg = new Configuration();
		cfg.setDefaultEncoding(defaultCharacter);
		cfg.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX);
		cfg.setDirectoryForTemplateLoading(new File(generateCodeTemplatePath));
		cfg.setEncoding(Locale.getDefault(), defaultCharacter);
	}

	public Configuration getCfg() {
		return cfg;
	}

}